package dao;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import databean.PriceResearchBean;

import utility.Util_Research;

public class GetPriceResearchDAO {
	
	private static String timestamp;
	private static String processingTime;
	private static String callsRemaining;
	
	
	public static String getTimestamp() {
		return timestamp;
	}

	public static String getProcessingTime() {
		return processingTime;
	}

	public static String getCallsRemaining() {
		return callsRemaining;
	}

	public static List<PriceResearchBean> getPriceResearch(String keyword) {
		
		HashMap<String,String> data=new HashMap<String,String>();
		data.put("QueryKeywords", keyword);
		
		Document response = Util_Research.sendRequest("GetPriceResearch.txt", data);
		
		
		//process response
		
		timestamp = response.getElementsByTagName("Timestamp").item(0).getChildNodes().item(0).getNodeValue();
		processingTime = response.getElementsByTagName("ProcessingTime").item(0).getChildNodes().item(0).getNodeValue();
		callsRemaining = response.getElementsByTagName("CallsRemaining").item(0).getChildNodes().item(0).getNodeValue();

		
		NodeList ids=response.getElementsByTagName("Date");
		int len=ids.getLength();
		
		NodeList totalSales = response.getElementsByTagName("TotalSales");
		NodeList totalSoldItems = response.getElementsByTagName("TotalSoldItems");
		NodeList averageSoldPrices = response.getElementsByTagName("AverageSoldPrice");
		NodeList maxSoldPrices = response.getElementsByTagName("MaxSoldPrice");
		NodeList minSoldPrices = response.getElementsByTagName("MinSoldPrice");
		
		List<PriceResearchBean> beans = new ArrayList<PriceResearchBean>();
		
		//adding first one
		PriceResearchBean bean = new PriceResearchBean();
		bean.setDate("Still Ongoing");
		bean.setTotalSales(geti(totalSales,0));
		bean.setTotalSoldItems(geti(totalSoldItems,0));
		bean.setAverageSoldPrice(geti(averageSoldPrices,0));
		bean.setMaxSoldPrice(geti(maxSoldPrices,0));
		bean.setMinSoldPrice(geti(minSoldPrices,0));
		beans.add(bean);
		
		for(int i=0;i<len;i++){
			
			bean = new PriceResearchBean();
			bean.setDate(geti(ids,i));
			bean.setTotalSales(geti(totalSales,i+1));
			bean.setTotalSoldItems(geti(totalSoldItems,i+1));
			bean.setAverageSoldPrice(geti(averageSoldPrices,i+1));
			bean.setMaxSoldPrice(geti(maxSoldPrices,i+1));
			bean.setMinSoldPrice(geti(minSoldPrices,i+1));
			beans.add(bean);
			
		}
		return beans;
	}
	
    private static String geti(NodeList list,int i){
    	return list.item(i).getChildNodes()
		.item(0).getNodeValue();
    }
	
}
 